package io.github.uicdb.liba.api.register;

import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.SlotItemHandler;
import org.jetbrains.annotations.Nullable;

import javax.annotation.Nonnull;
import java.util.concurrent.atomic.AtomicReference;

public class LazyItemMenu extends LazyMenuBase {

        protected final ItemStack itemStack;
        protected final InteractionHand hand;
        public LazyItemMenu(@Nullable MenuType<?> pMenuType, int pContainerId, Inventory playerInv, @Nonnull FriendlyByteBuf extraData) {
            super(pMenuType, pContainerId,playerInv,extraData);
              hand = extraData.readBoolean()?InteractionHand.MAIN_HAND:InteractionHand.OFF_HAND;
            this.itemStack=player.getItemInHand(hand);
        }


    /**
         * @return 屏幕是否能够开启
         */
        @Override
        public boolean stillValid(@Nonnull Player player) {
            return player.isAlive()&&player.getItemInHand(hand).equals(itemStack);
        }

        /**
         * 将ItemHandler的某个格子转化为slot
         *
         * @param index 格子索引
         * @param x     屏幕坐标X
         * @param y     屏幕坐标Y
         * @return SlotItemHandler，可用于addSlotBox
         */
        public SlotItemHandler newSlot(int index, int x, int y) {
            AtomicReference<SlotItemHandler> result = new AtomicReference<>();
            itemStack.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY).ifPresent(iItemHandler -> {
                result.set(newSlot(iItemHandler, index, x, y));
            });
            return result.get();
        }

        @Override
        public String toString() {
            return "LazyMenu{" +
                    "playerInv=" + playerInv +
                    ", extraData=" + extraData +
                    ", player=" + player +
                    ", level=" + level +
                    '}';
        }

}
